package com.pzb.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pzb.common.config.WechatConfig;
import com.pzb.common.utils.StringUtils;
import com.pzb.common.utils.http.HttpUtils;
import com.pzb.wechat.domain.TemplateUploadModel;
import com.pzb.wechat.service.IWechatAuthorizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pzb.wechat.mapper.WechatComponentMapper;
import com.pzb.wechat.domain.WechatComponent;
import com.pzb.wechat.service.IWechatComponentService;

import java.util.Date;

/**
 * 三方信息Service业务层处理
 * 
 * @author Mr_Wu
 * @date 2021-12-31
 */
@Service
public class WechatComponentServiceImpl implements IWechatComponentService 
{
    private static final Logger log = LoggerFactory.getLogger(WechatComponentServiceImpl.class);

    private final String API_URL = "https://api.weixin.qq.com/cgi-bin/component";

    @Autowired
    private WechatComponentMapper wechatComponentMapper;
    @Autowired
    private IWechatAuthorizationService authorizationService;

    /**
     * 查询三方信息
     *
     * @return 三方信息
     */
    @Override
    public WechatComponent selectWechatComponent()
    {
        return wechatComponentMapper.selectWechatComponent();
    }

    /**
     * 修改三方信息
     * 
     * @param wechatComponent 三方信息
     * @return 结果
     */
    @Override
    public int updateWechatComponent(WechatComponent wechatComponent)
    {
        return wechatComponentMapper.updateWechatComponent(wechatComponent);
    }

    @Override
    public String getApiComponentToken() {
        //先查询是否过期
        WechatComponent component = selectWechatComponent();
        //计算时间差
        Double min = (new Date().getTime()-component.getTokenCreateTime().getTime())/(1000*60)*1.0;
        //如果大于110分钟重新获取
        if(min < 110){
            return component.getComponentAccessToken();
        }
        //获取AccessToken
        JSONObject param = new JSONObject();
        param.put("component_appid", WechatConfig.getAppId());
        param.put("component_appsecret", WechatConfig.getAppSecret());
        param.put("component_verify_ticket", component.getTicket());
        String result =  HttpUtils.sendPost(API_URL+"/api_component_token",param.toString());
        JSONObject object = JSONObject.parseObject(result);
        String component_access_token = object.getString("component_access_token");
        if(StringUtils.isNotBlank(component_access_token)){
            component.setComponentAccessToken(component_access_token);
            component.setTokenCreateTime(new Date());
            component.setTicket(null);
            component.setTicketCreateTime(null);
            updateWechatComponent(component);
        }else {
            log.info("获取AccessToken失败=================>"+result);
        }
        return component_access_token;
    }

    //获取预授权码
    @Override
    public String createPreauthcode(){
        JSONObject param = new JSONObject();
        param.put("component_appid", WechatConfig.getAppId());
        String accessToken = getApiComponentToken();
        String result =  HttpUtils.sendPost(API_URL+"/api_create_preauthcode?component_access_token="+accessToken,param.toString());
        JSONObject object = JSONObject.parseObject(result);
        String pre_auth_code = object.getString("pre_auth_code");
        if(StringUtils.isBlank(pre_auth_code)){
            log.info("获取获取预授权码失败=================>"+result);
        }
        return pre_auth_code;
    }

    //获取用户授权信息
    @Override
    public JSONObject queryAuth(String authorizationCode) {
        JSONObject param = new JSONObject();
        param.put("component_appid", WechatConfig.getAppId());
        param.put("authorization_code", authorizationCode);
        String accessToken = getApiComponentToken();
        String result =  HttpUtils.sendPost(API_URL+"/api_query_auth?component_access_token="+accessToken,param.toString());
        return JSONObject.parseObject(result);
    }

    //获取授权方账号信息
    @Override
    public JSONObject getAuthorizerInfo(String authorizerAppid) {
        JSONObject param = new JSONObject();
        param.put("component_appid", WechatConfig.getAppId());
        param.put("authorizer_appid", authorizerAppid);
        String accessToken = getApiComponentToken();
        String result =  HttpUtils.sendPost(API_URL+"/api_get_authorizer_info?component_access_token="+accessToken,param.toString());
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject gettemplatedraftlist() {
        String access_token =getApiComponentToken();
        String url = "https://api.weixin.qq.com/wxa/gettemplatedraftlist";
        String result = HttpUtils.sendGet(url,"access_token="+access_token);
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject gettemplatelist() {
        String access_token =getApiComponentToken();
        String url = "https://api.weixin.qq.com/wxa/gettemplatelist";
        String result = HttpUtils.sendGet(url,"access_token="+access_token);
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject deletetemplate(Long template_id) {
        String access_token =getApiComponentToken();
        String url = "https://api.weixin.qq.com/wxa/deletetemplate?access_token="+access_token;
        JSONObject param = new JSONObject();
        param.put("template_id", template_id);
        String result = HttpUtils.sendPost(url,param.toString());
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject addtotemplate(Integer draft_id, Integer template_type) {
        String access_token =getApiComponentToken();
        String url = "https://api.weixin.qq.com/wxa/addtotemplate?access_token="+access_token;
        JSONObject param = new JSONObject();
        param.put("draft_id", draft_id);
        param.put("template_type", template_type);
        String result = HttpUtils.sendPost(url,param.toString());
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject templateUpload(TemplateUploadModel uploadModel) {
        String access_token = authorizationService.getAuthorizerAccessToken(uploadModel.getAppid());
        String url = "https://api.weixin.qq.com/wxa/commit?access_token="+access_token;
        JSONObject param = new JSONObject();
        param.put("template_id", uploadModel.getTemplate_id()+"");
        param.put("user_version", uploadModel.getUser_version());
        param.put("user_desc", uploadModel.getUser_desc());
        JSONObject ext_json = new JSONObject();
        ext_json.put("extEnable","true");
        ext_json.put("extAppid",uploadModel.getAppid());
        ext_json.put("directCommit","false");
        JSONObject ext = new JSONObject();
        ext.put("extAppid",uploadModel.getAppid());
        ext_json.put("ext",ext);
        param.put("ext_json",ext_json.toJSONString());
        String result = HttpUtils.sendPost(url,param.toString());
        return JSONObject.parseObject(result);

    }
}
